/*
 *  Copyright (C) 2011 Glenn Rune Strandbråten 
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package myrmidia.UI;

import java.awt.print.PrinterException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Collection;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import jcolibri.cbrcore.CBRCase;
import myrmidia.UI.Resources.MultipleResults;
import myrmidia.UI.Resources.WindowCloser;
import myrmidia.Util.CollectionControl;
import myrmidia.Warhammer.Case;

/**
 * User interface to allow a user to display and print the case data
 * (army information)
 * @author Glenn Rune Strandbråten
 * @version 1.0
 */
public class PrintUI extends javax.swing.JDialog implements MultipleResults{

    private Collection<CBRCase> cbrCases;
    private int displaying = -1;

    /**
     * Creates new form PrintUI
     * @param cbrCases The collection of CBRCases available for printing
     * @param displaying int The current displaying case
     * @param parent The JFrame parent
     * @param modal boolean determining if the dialog is of type modal
     */
    public PrintUI(Collection<CBRCase> cbrCases, JFrame parent,int displaying, boolean modal) {
        super(parent,modal);
        initComponents();
        addWindowListener(new WindowCloser());
        setLocationRelativeTo(parent);
        this.cbrCases = cbrCases;
        this.displaying=displaying-1;
        if(cbrCases!=null){
            displayNextResult();
        }
        createOutputStream();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        navigationPane = new javax.swing.JPanel();
        previousCaseButton = new javax.swing.JButton();
        nextCaseButton = new javax.swing.JButton();
        displayCountLabel = new javax.swing.JLabel();
        displayInfoLabel = new javax.swing.JLabel();
        doneButton = new javax.swing.JButton();
        printScroll = new javax.swing.JScrollPane();
        printArea = new javax.swing.JTextArea();
        printButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Myrmidia - Print");

        navigationPane.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        previousCaseButton.setText("<");
        previousCaseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                previousCaseButtonActionPerformed(evt);
            }
        });

        nextCaseButton.setText(">");
        nextCaseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nextCaseButtonActionPerformed(evt);
            }
        });

        displayCountLabel.setText("1/1");

        displayInfoLabel.setText("Displaying case (army)");

        doneButton.setMnemonic('d');
        doneButton.setText("Done");
        doneButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                doneButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout navigationPaneLayout = new javax.swing.GroupLayout(navigationPane);
        navigationPane.setLayout(navigationPaneLayout);
        navigationPaneLayout.setHorizontalGroup(
            navigationPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(navigationPaneLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(previousCaseButton)
                .addGap(18, 18, 18)
                .addComponent(displayInfoLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(displayCountLabel)
                .addGap(17, 17, 17)
                .addComponent(nextCaseButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 320, Short.MAX_VALUE)
                .addComponent(doneButton)
                .addContainerGap())
        );
        navigationPaneLayout.setVerticalGroup(
            navigationPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, navigationPaneLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(navigationPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nextCaseButton)
                    .addComponent(displayInfoLabel)
                    .addComponent(previousCaseButton)
                    .addComponent(displayCountLabel)
                    .addComponent(doneButton))
                .addContainerGap())
        );

        printArea.setColumns(20);
        printArea.setEditable(false);
        printArea.setFont(new java.awt.Font("Verdana", 0, 12)); // NOI18N
        printArea.setRows(5);
        printScroll.setViewportView(printArea);

        printButton.setMnemonic('p');
        printButton.setText("Print");
        printButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                printButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(navigationPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(583, Short.MAX_VALUE)
                .addComponent(printButton)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(printScroll, javax.swing.GroupLayout.DEFAULT_SIZE, 628, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(navigationPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(printButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(printScroll, javax.swing.GroupLayout.DEFAULT_SIZE, 301, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Action performed when the previousCaseButton is selected
     * @param evt The ActionEvent trigger
     */
    private void previousCaseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_previousCaseButtonActionPerformed
        if(cbrCases!=null)
            displayPreviousResult();
}//GEN-LAST:event_previousCaseButtonActionPerformed

    /**
     * Action performed when the nextCaseButton is selected
     * @param evt The ActionEvent trigger
     */
    private void nextCaseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nextCaseButtonActionPerformed
        if(cbrCases!=null)
            displayNextResult();
}//GEN-LAST:event_nextCaseButtonActionPerformed

    /**
     * Action performed when the doneButton is selected
     * @param evt The ActionEvent trigger
     */
    private void doneButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_doneButtonActionPerformed
        dispose();
}//GEN-LAST:event_doneButtonActionPerformed

    /**
     * Action performed when the printButton is selected
     * @param evt The ActionEvent trigger
     */
    private void printButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_printButtonActionPerformed
        try {
            if(!printArea.getText().isEmpty())
                printArea.print();
        }
        catch (PrinterException ex) {}
    }//GEN-LAST:event_printButtonActionPerformed

    public final void displayPreviousResult() {
        displaying = (displaying==0) ? cbrCases.size()-1 : displaying-1;
        displayResult();
    }

    public final void displayNextResult() {
        displaying = (displaying==cbrCases.size()-1) ? 0 : displaying+1;
        displayResult();
    }

    public void displayResult() {
        printArea.setText("");
        CBRCase cbr=(CBRCase)CollectionControl.getItemAt(cbrCases,displaying);
        Case _case = (Case) cbr.getSolution();
        myrmidia.Util.PrintFactory.printCase(_case, true,createOutputStream());
    }

    public void populateUnitsTable() throws UnsupportedOperationException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * Method to create an output stream bound to the JTextArea, this
     * OutputStream will superceede the default System.out permitting a
     * System.out call to be written to the bound JTextArea
     * @return The created OutputStream bound to the JTextArea
     */
    private OutputStream createOutputStream() {
        OutputStream out = new OutputStream() {
            @Override
            public void write(int b) throws IOException {
                updateTextArea(String.valueOf((char) b));
            }
            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                updateTextArea(new String(b, off, len));
            }
            @Override
            public void write(byte[] b) throws IOException {
                write(b, 0, b.length);
            }
        };
    System.setOut(new PrintStream(out, true));
    return out;
    }

    /**
     * Method used by the bound OutputStream to print System.out calls to the
     * textArea
     * @param text String the text to be printed to the JTextArea
     */
    private void updateTextArea(final String text) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                printArea.append(text);
                printArea.setCaretPosition(0);
            }
        });
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new PrintUI(null,null,0,false).setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel displayCountLabel;
    private javax.swing.JLabel displayInfoLabel;
    private javax.swing.JButton doneButton;
    private javax.swing.JPanel navigationPane;
    private javax.swing.JButton nextCaseButton;
    private javax.swing.JButton previousCaseButton;
    private javax.swing.JTextArea printArea;
    private javax.swing.JButton printButton;
    private javax.swing.JScrollPane printScroll;
    // End of variables declaration//GEN-END:variables
}
